package com.joker.aigc.oj.service.impl.template.java;



import com.joker.aigc.constant.SandBoxConstants;
import com.joker.aigc.oj.domain.dto.code.ExecuteResult;
import com.joker.aigc.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class JavaNativeArgsSandbox extends JavaSandboxTemplate {


    @Override
    protected List<ExecuteResult> runCode(String dir, List<String> inputList) throws IOException {
        List<ExecuteResult> messages = new ArrayList<>();
        for (String input : inputList) {
            //Linux下的命令
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", dir, input);
            //Windows下命令
            // String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", dir, input);
            Process runProcess = Runtime.getRuntime().exec(runCmd);
            // 超时控制
            new Thread(() -> {
                try {
                    Thread.sleep(SandBoxConstants.TIME_OUT);
                    log.info("超时了，中断");
                    runProcess.destroy();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
            ExecuteResult executeResult = ProcessUtils.getProcessMessage(runProcess, "运行");
            messages.add(executeResult);
        }
        return messages;
    }
}
